package dLogistic.domain.service;

import dLogistic.domain.model.sharedValueObjects.Adres;
import dLogistic.infrastructure.persistence.hibernate.HibernateUtil;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Przemek on 2014-10-26.
 */

public class GeolokalizacjaService {
    private static SessionFactory factory;

    /*

    select uuid, square(latitude - :x) + square(longitude - :y) from Adres
where longitude is not null and latitude is not null and typ = :typ
order by 2 asc
;
     */
    private static final String URLbasic = "http://maps.googleapis.com/maps/api/geocode/json";

    public ArrayList<String> wyznaczGeolokalizacje(String ulica, String numer_domu, String numer_lokalu, String miasto, String kod_pocztowy){

        ArrayList<String> arr = new ArrayList<String>();

        URL url;
        InputStream is = null;
        DataInputStream dis;
        JSONParser parser = new JSONParser();

        String geo_adres = kod_pocztowy + "," + miasto + "," + ulica + "+" + numer_domu;
        if (numer_lokalu != ""){
            geo_adres = geo_adres + "+" + numer_lokalu;
        }


        try {
            url = new URL(URLbasic + "?address=" + geo_adres);
            //arr.add(URLbasic + "?address=" + geo_adres);
            Reader in = new InputStreamReader(url.openStream());
            JSONObject jsonObject = (JSONObject) parser.parse(in);

//            JSONObject status = (JSONObject) jsonObject.get("status");

           // if (status.toString().toUpperCase() == "OK") {
                JSONArray results = (JSONArray) jsonObject.get("results");
                JSONObject geometry1 = (JSONObject) results.get(0);
                JSONObject geometry = (JSONObject) geometry1.get("geometry");
                JSONObject location = (JSONObject) geometry.get("location");
                arr.add(location.get("lat").toString());
                arr.add(location.get("lng").toString());
            //}
            //else{

                arr.add("0.0");
                arr.add("0.0");
//            }
            //arr.add(in.toString());

        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {

        }

        return arr;
    }

    public ArrayList<String> ZwrocWspolrzedneXY(String uuid_parent){
        factory = HibernateUtil.getSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction transaction = session.beginTransaction();

        ArrayList<String> wspolrzedne = new ArrayList<String>();

        String sql = "select * from Adres where uuid_parent = :uuid_parent";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity(Adres.class);
        query.setParameter("uuid_parent", uuid_parent);
        List results = query.list();
        transaction.rollback();
        if (!results.isEmpty()){
            Adres adres = (Adres) results.get(0);
            //wspolrzedne.add(results.get);
            wspolrzedne.add(adres.latitude().toString().replace(",","."));
            wspolrzedne.add(adres.longitude().toString().replace(",","."));
            return wspolrzedne;
        }
        else {
            wspolrzedne.add("0");
            wspolrzedne.add("0");
            return wspolrzedne;
        }
    }

}
